package com.boot.rocketmq.controller;


import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("rocketmq")
public class DemoController {


    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @PostMapping("/sendOneWay")
    public String testSendOneWay() {
        rocketMQTemplate.sendOneWay("topic_test", MessageBuilder.withPayload("测试单向消息").build());
        return "success";
    }

    @PostMapping("/sendSync")
    public SendResult testSyncSend() {
        SendResult result = rocketMQTemplate.syncSend("topic_sync", MessageBuilder.withPayload("测试同步消息").build());
        System.out.println("发送状态：" + result.getSendStatus() + " 消息id：" + result.getMsgId());
        return result;
    }


    @PostMapping("/sendAsync")
    public String testAsyncSend() {
        rocketMQTemplate.asyncSend("topic_async", MessageBuilder.withPayload("测试异步消息").build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送状态：" + sendResult.getSendStatus() + " 消息id：" + sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable e) {
                System.out.printf("消息发送失败, exception: %s\n", e.getMessage());
            }
        });
        return "success";
    }


    @PostMapping("/sendBatch")
    public SendResult testBatchSend() {
        List<Message<String>> messages = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            messages.add(MessageBuilder.withPayload("测试批量消息" + i).build());
        }
        SendResult result = rocketMQTemplate.syncSend("topic_order", messages);
        System.out.println("发送状态：" + result.getSendStatus() + " 消息id：" + result.getMsgId());
        return result;
    }


    @PostMapping("/sendDelay")
    public SendResult testDelaySend() {
        //在RocketMQ中，timeout（超时时间）是指消息发送的最大等待时间。当你发送一个消息时，系统会等待一定的时间来获取发送结果，这个等待的时间就是超时时间。单位ms
        //延迟级别 "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h" 2对应5s
        SendResult result = rocketMQTemplate.syncSend("topic_delay", MessageBuilder.withPayload("测试延迟消息").build(), 2000, 2);
        System.out.println("发送状态：" + result.getSendStatus() + " 消息id：" + result.getMsgId());
        return result;
    }

}
